package pm.oo;

import com.sun.star.frame.XFrame;
import com.sun.star.frame.XLayoutManager;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;
import com.sun.star.beans.UnknownPropertyException;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.comp.helper.BootstrapException;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import pm.oo.util.FramesCreator;
import pm.oo.util.DocumentLoader;
import pm.oo.util.Executor;
import pm.oo.util.OfficeConnection;
import pm.PM;

public class OOModuleImpl implements OOModule {
    public static final String VIEW_NAME = "PM_VIEW";
    protected XFrame currentXFrame;
    protected XComponent currentXDocument;

    public void loadDocument(File file, NativeOOViewComponent viewComponent) throws IOException {
        String ooUrl = "file:///" + file.getCanonicalPath().replace('\\', '/');
        currentXFrame = FramesCreator.createViewFrame(VIEW_NAME, viewComponent);
        final PropertyValue[] propertyValues = DocumentLoader.setupLoadProps();
        currentXDocument = DocumentLoader.loadDocument(currentXFrame, ooUrl, propertyValues);
        //System.out.println(currentXDocument == null ? "null" : "not null");
        if (!PM.DEBUG) {
            try {
                XPropertySet xPropSet = (com.sun.star.beans.XPropertySet) UnoRuntime.queryInterface(
                        com.sun.star.beans.XPropertySet.class, currentXFrame);
                XLayoutManager layoutManager = (XLayoutManager) UnoRuntime.queryInterface(
                        XLayoutManager.class, xPropSet.getPropertyValue("LayoutManager"));
                layoutManager.setVisible(!layoutManager.isVisible());
                //currentXFrame.getContainerWindow().setEnable(layoutManager.isVisible());
            } catch (
                    UnknownPropertyException e) {
                e.printStackTrace();
            } catch (
                    WrappedTargetException e) {
                e.printStackTrace();
            }
        }
    }

    public void closeCurrentDocument() {
        DocumentLoader.closeDocument(currentXDocument);
    }

    public XFrame getCurrentFrame() {
        return currentXFrame;
    }

    public XComponent getCurrentDocument() {
        return currentXDocument;
    }

    public void nextPage() {
        Executor.dispatch(currentXFrame, ".uno:PageUp", null);
    }

    public void prevPage() {
        Executor.dispatch(currentXFrame, ".uno:PageDown", null);
    }

    public void print(Map props) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void createConnection() {
        try {
            OfficeConnection.createConnection();
        } catch (BootstrapException e) {
            e.printStackTrace();
        }
    }
}
